﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;

namespace WZVTC.SoftDev.DDDFW.Global
{
    public class DataTableConverter
    {
        public static DataTable List2DataTable(string[] columns,string[] propertyNames , IList items)
        {
            DataTable result = new DataTable();
            if(columns==null||propertyNames==null||columns.Length!=propertyNames.Length) return result;
            foreach (string s in columns)
                result.Columns.Add(s);
            if(items.Count>0)
            {
                Type t=items[0].GetType();
                PropertyInfo[] pi_array=new PropertyInfo[propertyNames.Length];
                int i=0;
                foreach(string s in propertyNames)
                {
                    foreach (PropertyInfo info in t.GetProperties())
                    {
                        if(info.Name.Equals(s))
                        {
                            pi_array[i]=info;
                            i++;
                        }
                    }
                }
                if(i!=propertyNames.Length) return result;
                foreach(Object item in items)
                {
                    object[] o_array=new object[i];
                    for(int j=0;j<o_array.Length;j++)
                    {
                        o_array[j]=pi_array[j].GetValue(item,null);
                    }
                    result.Rows.Add(o_array);
                }
            }
            return result;
        }
        public static DataTable List2DataTable(IList items)
        {
           // DataTable result = new DataTable();
            if (items.Count == 0) return List2DataTable(null,null,null);
            Type t=items[0].GetType();
            List<string> piNames=new List<string>();
            foreach (PropertyInfo info in t.GetProperties())
            {
                 Object o = info.GetValue(items[0], null);
                 //通过判断此属性是否存在名为Count的属性来决定此属性是否是集合。因为我还找不到一个判断此属性是否是一个集合
                 //这个是一个取巧与临时的办法，但似乎工作的很好！              
                 if(o.GetType().GetProperty("Count")==null)
                    piNames.Add(info.Name);
                  
             }
            return List2DataTable(piNames.ToArray(),piNames.ToArray(),items);
        }
    }
}
